<template>
  <div class="good-container" ref="parent">
    <div class="good-top">
      <div class="good-search">
        <el-input
          placeholder="请输入你要搜索的展厅"
          v-model="queryParams.key"
          @keyup.native.enter="search"
          size="small"
          @clear="search"
          clearable
        ></el-input>
      </div>
      <div class="good-btn">
        <el-button type="primary" size="small" @click="isShowDialog = true">新增</el-button>
      </div>
    </div>

    <el-scrollbar style="height: calc(100vh - 190px)" class="scrollbar" id="scroll-bar">
      <el-table
        ref="table"
        :row-key="(row) => row.data_id"
        :data="list"
        v-loading="loading"
        :expand-row-keys="expandedRowKeys"
        @expand-change="expandChange"
      >
        <el-table-column type="expand">
          <template slot-scope="scope">
            <div class="subTable">
              <el-table :data="[...scope.row.work_list]">
                <el-table-column label="作品列表">
                  <template slot-scope="subScope">
                    <el-link type="primary">{{ subScope.row.name }}</el-link>
                  </template>
                </el-table-column>
                <el-table-column label="作品类型">
                  <template slot-scope="subScope">
                    <el-link type="primary">{{ subScope.row.type == 0 ? '图片' : '视频' }}</el-link>
                  </template>
                </el-table-column>
                <el-table-column label="封面图">
                  <template slot-scope="subScope">
                    <el-image
                      v-if="subScope.row.title_page"
                      style="width: 100px; height: 40px"
                      :src="subScope.row.title_page"
                      :preview-src-list="[subScope.row.title_page]"
                      fit="cover"
                    ></el-image>
                    <span v-else>暂无图片</span>
                  </template>
                </el-table-column>
                <el-table-column label="大图/视频">
                  <template slot-scope="subScope">
                    <el-image
                      v-if="subScope.row.opus_id && subScope.row.opus_id.length > 0 && subScope.row.type == 0"
                      style="width: 100px; height: 40px; cursor: pointer"
                      :src="getBigImg(subScope.row.opus_id[0].id)"
                      @click="lookBig(subScope.row)"
                      fit="cover"
                    ></el-image>
                    <div v-else-if="subScope.row.type == 1 && subScope.row.video_url">
                      {{ '已上传' }}
                    </div>
                    <span v-else>暂无数据</span>
                  </template>
                </el-table-column>
                <el-table-column label="是否推荐">
                  <template slot-scope="scope">
                    <el-switch
                      v-model="scope.row.recommend"
                      @change="onRecommend(scope.row)"
                      :active-value="1"
                      :inactive-value="0"
                    ></el-switch>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="400px">
                  <template slot-scope="subScope">
                    <el-upload
                      action="/ws"
                      class="avatar-uploader"
                      style="width: 90px; float: left"
                      :show-file-list="false"
                      :on-progress="uploadVideoProcess"
                      :on-success="handleVideoSuccess"
                      :before-upload="
                        (file) => {
                          beforeMapUpload(file, subScope.row);
                        }
                      "
                    >
                      <el-button size="mini">
                        {{ subScope.row.type == 0 ? '上传大图' : '上传视频' }}
                      </el-button>
                      <el-progress
                        v-if="videoFlag && uploadVideoId == subScope.row.data_id"
                        :percentage="videoUploadPercent"
                        style="margin-top: 30px"
                      ></el-progress>
                    </el-upload>
                    <el-upload
                      action="/ws"
                      class="avatar-uploader"
                      style="width: 90px; float: left"
                      :show-file-list="false"
                      :before-upload="
                        (file) => {
                          beforeWorkAvatarUpload(file, subScope.row.data_id);
                        }
                      "
                    >
                      <el-button size="mini">上传封面</el-button>
                    </el-upload>
                    <el-button type="primary" size="mini" @click="editWork(subScope.row)">修改</el-button>
                    <el-button type="danger" size="mini" @click="delWork(subScope.row)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
              <paging ref="workPage" :func="getWorkList"></paging>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="id" prop="data_id"></el-table-column>
        <el-table-column label="展厅banner">
          <template slot-scope="scope">
            <el-image
              v-if="scope.row.title_page"
              style="width: 100px; height: 40px"
              :src="scope.row.title_page"
              :preview-src-list="[scope.row.title_page]"
              fit="cover"
            ></el-image>
            <span v-else>暂无图片</span>
          </template>
        </el-table-column>
        <!-- <el-table-column label="背景图建议尺寸" width="160" prop="size">
          <template>
            <span style="text-align: center;">
              1920 * 520
            </span>
          </template>
        </el-table-column> -->
        <el-table-column label="展厅名称" prop="name"></el-table-column>
        <el-table-column label="操作" width="450">
          <template slot-scope="scope">
            <el-upload
              action=""
              class="avatar-uploader"
              style="width: 104px; float: left"
              :show-file-list="false"
              :before-upload="
                (file) => {
                  beforeAvatarUpload(file, scope.row.data_id);
                }
              "
            >
              <el-button size="mini">上传banner</el-button>
            </el-upload>
            <!-- <el-button type="primary" @click="onShowDrawer(scope.row)" size="mini">详情</el-button> -->
            <el-button size="mini" @click="quoteArt(scope.row.data_id)">引用作品</el-button>
            <el-button type="primary" size="mini" @click="addWork(scope.row)">新增</el-button>
            <el-button type="primary" @click="updSpecialSub(scope.row.data_id, scope.row)" size="mini">修改</el-button>
            <el-button type="danger" @click="delStadiums(scope.row.data_id)" size="mini">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-scrollbar>

    <paging ref="page" :func="getList"></paging>

    <el-dialog @click="closeWorkWind" title="引用作品" :visible.sync="showArtDialog">
      <el-form :model="artForm" :rules="workRules" ref="artForm" label-width="80px" class="demo-dataParams">
        <el-form-item label="艺术品" prop="art_id">
          <el-select
            v-model="artForm.art_id"
            remote
            filterable
            :remote-method="remoteArtMethod"
            :loading="queryLoading"
            @change="artChange"
          >
            <el-option v-for="item in artList" :key="item.data_id" :label="item.name" :value="item.data_id"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showArtDialog = false">取 消</el-button>
        <el-button type="primary" @click="artSubmit">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog @click="closeWorkWind" title="新增作品" :visible.sync="showWorkDialog">
      <el-form :model="workForm" :rules="workRules" ref="workForm" label-width="80px" class="demo-dataParams">
        <el-form-item label="作品名称" prop="name">
          <el-input v-model="workForm.name"></el-input>
        </el-form-item>
        <el-form-item label="艺术家" prop="art_id">
          <el-select
            v-model="workForm.art_id"
            remote
            filterable
            :remote-method="remoteMethod"
            :loading="queryLoading"
            @change="workChange"
          >
            <el-option
              v-for="item in userList"
              :key="item.data_id"
              :label="item.name"
              :value="item.data_id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="作品类型" prop="type">
          <el-radio-group v-model="workForm.type">
            <el-radio :label="0">图片</el-radio>
            <el-radio :label="1">视频</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否推荐" prop="作品类型">
          <el-switch v-model="workForm.recommend" :active-value="1" :inactive-value="0"></el-switch>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showWorkDialog = false">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog @closed="onClose" title="提示" :visible.sync="isShowDialog">
      <el-form :model="params" :rules="rules" ref="dataParams" label-width="80px" class="demo-dataParams">
        <el-form-item label="名称" prop="name">
          <el-input v-model="params.name"></el-input>
        </el-form-item>
        <el-form-item label="介绍" prop="introduction">
          <el-input type="textarea" v-model="params.introduction"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isShowDialog = false">取 消</el-button>
        <el-button type="primary" @click="dialogConfirm">确 定</el-button>
      </span>
    </el-dialog>

    <el-drawer :title="obj.name" :visible.sync="isShowDrawer" direction="rtl">
      <div class="show-detail">
        <div class="detail-item">
          <div class="item-title">作品详情：</div>
          <div class="item-content">{{ obj }}</div>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script>
  import uploadManage from '@/api/upload';
  import goodManage from '@/api/good';
  import paging from '@/components/paging';
  import articleManage from '@/api/article';
  import videoManage from '@/api/video';
  import artManage from '@/api/works';
  import artisManage from '@/api/artis';
  import { getImageUrl, getBigImg } from '@/utils/image';
  import Vue from 'vue';
  import { qiniuUploadFile } from '@/utils/QiniuUpload';

  export default {
    components: {
      paging,
    },
    data() {
      return {
        list: [],
        videoUploadPercent: 0,
        videoFlag: false,
        value: '',
        timer: null,
        queryParams: {
          key: '',
          // min_create_time: '',
        },
        activeRow: {},
        isShowDialog: false,
        isShowDrawer: false,
        params: {
          name: '',
          introduction: '',
        },
        expandedRowKeys: [100010],
        workForm: {
          stadiums_id: '',
          name: '',
          art_id: '',
          type: 0,
          recommend: 0,
          opus_id: [],
          title_page: '',
        },
        artForm: {
          art_id: '',
        },

        obj: {},
        rules: {
          name: [{ required: true, message: '请输入展厅名称', trigger: 'blur' }],
          introduction: [{ required: true, message: '请输入展厅介绍', trigger: 'change' }],
        },
        workRules: {
          name: [{ required: true, message: '请输入作品名称', trigger: 'blur' }],
          type: [{ required: true, message: '请选择作品类型', trigger: 'change' }],
        },
        artRules: {
          art_id: [{ required: true, message: '请选择艺术品', trigger: 'change' }],
        },
        updId: '',
        updWorkId: '',
        menuId: '',
        userList: [],
        artList: [],
        loading: false,
        queryLoading: false,
        showWorkDialog: false,
        showArtDialog: false,
      };
    },
    watch: {},
    mounted() {
      this.refresh();
      this.getArtType();
      this.getArt();
    },
    methods: {
      async remoteMethod(query) {
        // if (!query) return;
        this.queryLoading = true;
        let userRes = await artisManage.getArtis({ key: query, notPagination: true });
        this.userList = userRes.item_list;
        this.queryLoading = false;
      },

      async remoteArtMethod(query) {
        // if (!query) return;
        this.queryLoading = true;
        let userRes = await artManage.getArt({ key: query, notPagination: true });
        this.artList = userRes.item_list;
        this.queryLoading = false;
      },
      add(type) {
        this[type].push({});
      },
      workChange() {},
      artChange(id) {
        let obj = this.artList.find((item) => {
          return item.data_id === id;
        });
        let { art_id, name, opus_id, recommend, work_type, work_video, thumbnail } = obj;
        this.workForm = {
          stadiums_id: this.workForm.stadiums_id,
          name,
          art_id,
          type: work_type === 2 ? 1 : 0,
          recommend,
          opus_id: opus_id || [],
          video: work_video,
          title_page: thumbnail,
        };
      },
      // 查看大图
      lookBig(data) {
        console.log(data);
        if (data.opus_id && data.opus_id.length > 0) {
          let { BasicDraw, BigImageShow } = require('../../../utils/main');
          let basicDraw = new BasicDraw(); // 创建基础渲染类
          basicDraw.zIndex = 9999;
          basicDraw.start(); // 开始渲染
          new BigImageShow().showBigImg(data.opus_id[0].id);

          document.getElementById('bigIamgeClose').addEventListener('click', (e) => {
            basicDraw.dispose();
            e.stopPropagation();
          });
        }
      },
      getBigImg,
      async getArtType() {
        let userRes = await artisManage.getArtis({ notPagination: true });
        this.userList = userRes.item_list;
      },
      async getArt() {
        let userRes = await artManage.getArt({ notPagination: true });
        this.artList = userRes.item_list;
      },
      remove(type, i) {
        this[type].splice(i, 1);
      },
      querySearchEssay(queryString, cb) {
        articleManage.getArticle({ key: queryString, notPagination: true }).then((res) => {
          res.item_list.forEach((m) => {
            m.value = m.title;
          });
          cb(res.item_list);
        });
      },
      querySearchVideo(queryString, cb) {
        videoManage.getVideoType({ key: queryString, notPagination: true }).then((res) => {
          res.item_list.forEach((m) => {
            m.value = m.video_name;
          });
          cb(res.item_list);
        });
      },
      querySearchWorks(queryString, cb) {
        artManage.getArt({ key: queryString, notPagination: true }).then((res) => {
          res.item_list.forEach((m) => {
            m.value = m.name;
          });
          cb(res.item_list);
        });
      },
      selectItem(type, i, m) {
        this[type][i].data_id = m.data_id;
      },
      contextMenu(r, column, e) {
        let rect = this.$refs.parent.getBoundingClientRect();
        this.$refs.menu.style.top = e.clientY - rect.top + 'px';
        this.$refs.menu.style.left = e.clientX - rect.left + 'px';
        // this.menuId = r.data_id;
        console.log(r);
        e.preventDefault();
      },
      refresh() {
        this.$refs.page.refresh();
      },
      search() {
        this.$refs.page.search();
      },
      expandChange(row, expandedRows) {
        this.expandedRowKeys = this.expandedRowKeys[0] == row.data_id ? [] : [row.data_id];
        this.activeRow = row;
        this.$nextTick(() => {
          if (this.$refs.workPage) this.$refs.workPage.refresh();
        });
      },
      handleVideoSuccess(res, file) {
        //视频上传成功之后返回视频地址
        this.videoFlag = false;
        this.videoUploadPercent = 0;
      },
      uploadVideoProcess(event, file, fileList) {
        this.videoFlag = true;
        this.videoUploadPercent = parseInt(file.percentage);
        console.log('this.videoUploadPercent', file.percentage);
      },
      async beforeMapUpload(file, row) {
        const formData = new FormData();
        formData.append('上传的key值', file);
        this.uploadVideoId = row.data_id;
        this.videoUploadPercent = 0;
        const timer = setInterval(() => {
          if (this.videoUploadPercent >= 99) {
            this.videoUploadPercent = 100;
            this.videoFlag = false;
            clearInterval(timer);
            return;
          }
          this.videoUploadPercent += 1;
        }, 20);
        if (row.type == 0) {
          let res = await qiniuUploadFile(file, 'good');
          if (res) {
            let url = res.key;
            let opus_id = await artManage.imageMap({
              image_list: [
                {
                  image_src_url: url,
                  image_src_type: 'local',
                  image_name: url.split('/')[2],
                  type: 1,
                  access_type: 0,
                  note: '',
                },
              ],
            });
            if (opus_id) {
              this.videoUploadPercent = 100;
              this.videoFlag = false;
              this.$message.success('上传成功');
              clearInterval(timer);
            }
            console.log('row.data_id', row.data_id);
            await goodManage.updWork(row.data_id, { opus_id });
          }
        } else {
          let res = await qiniuUploadFile(file, 'good');
          if (res) {
            await goodManage.updWork(row.data_id, { video_url: res.key });
            this.videoUploadPercent = 100;
            this.videoFlag = false;
            this.$message.success('上传成功');
            clearInterval(timer);
          }
        }

        // this.$loading().close()
        if (this.$refs.workPage) this.$refs.workPage.refresh();
      },
      getWorkList(callback) {
        console.log('this.activeRow', this.activeRow);
        // const index = this.list.findIndex(item => {
        //   return item.data_id == row.data_id
        // })
        // console.log(row, this.list, index)
        const params = {
          stadiums_id: this.activeRow.data_id,
        };
        goodManage.getWorkList(params).then(async (res) => {
          // this.list[index].work_list = res.item_list
          console.log(res);
          let total = res.total_count;
          this.list.forEach((ele) => {
            if (ele.data_id === this.activeRow.data_id) {
              console.log(ele.data_id, this.activeRow.data_id, res.item_list);
              Vue.set(ele, 'work_list', res.item_list);
            }
          });
          console.log('this.list', this.list);
          callback(res.item_list, total);
        });
      },
      getList(callback) {
        goodManage.getStadiums(this.queryParams).then(async (res) => {
          let total = res.total_count;
          for (let i = 0; i < res.item_list.length; i++) {
            let m = res.item_list[i];
            // try {
            m.work_list = [];
            // } catch {
            //   m.work_list = [];
            // }
          }
          this.list = res.item_list;
          this.$refs.table.clearSort();
          this.$refs.table.clearSelection();
          callback(this.list, total);
        });
      },
      async beforeAvatarUpload(file, id) {
        let res = await qiniuUploadFile(file, 'good');
        if (res) {
          await goodManage.updStadiums(id, { title_page: res.key });
          this.refresh();
        }

        // const formData = new FormData();
        // formData.append('上传的key值', file);
        // await goodManage.uploadImage(id, formData);
        // this.refresh();
      },
      async beforeWorkAvatarUpload(file, id) {
        let res = await qiniuUploadFile(file, 'good');
        if (res) {
          await goodManage.updWork(id, { title_page: res.key });
          this.refresh();
        }

        // const formData = new FormData();
        // formData.append('上传的key值', file);
        // await goodManage.uploadWorkImage(id, formData);

        if (this.$refs.workPage) this.$refs.workPage.refresh();
      },
      updSpecialSub(data_id, row) {
        this.isShowDialog = true;
        this.params = row;
        // this.value = [row.start_time, row.end_time];
        this.updId = data_id;
        // this.$nextTick(() => {
        //   this.essays = this.params.essay_list;
        //   this.videos = this.params.work_video_list;
        //   this.works = this.params.work_list;
        //   console.log(this.essays, this.works, this.videos);
        // });
      },
      closeWorkWind() {
        this.showWorkDialog = false;
        this.showArtDialog = false;
        this.workForm = {
          stadiums_id: '',
          name: '',
          art_id: '',
          type: 0,
          recommend: 0,
          opus_id: [],
          title_page: '',
        };
        if (this.$refs.workPage) {
          this.$refs.workPage.refresh();
        }
        this.$refs.workForm.resetFields();
      },
      addWork(row) {
        console.log(row.data_id);
        this.showWorkDialog = true;
        this.workForm.stadiums_id = row.data_id;
      },
      quoteArt(id) {
        this.showArtDialog = true;
        this.workForm.stadiums_id = id;
      },
      async onRecommend(row) {
        await goodManage.updWork(row.data_id, row);

        if (this.$refs.workPage) this.$refs.workPage.refresh();
      },
      editWork(row) {
        this.workForm = {
          ...row,
        };
        this.updWorkId = row.data_id;
        this.showWorkDialog = true;
        console.log(this.workForm);
      },
      delWork(row) {
        goodManage.delWork({ id: row.data_id }).then((res) => {
          this.$message.success('删除成功');
          this.$nextTick(() => {
            if (this.$refs.workPage) this.$refs.workPage.refresh();
          });
        });
      },
      async delStadiums(data_id) {
        this.$alert('是否确定删除该展厅', '删除', {
          confirmButtonText: '确定',
          callback: async (action) => {
            if (action === 'confirm') {
              await goodManage.delStadiums(data_id);
              this.refresh();
            }
          },
        });
      },
      async artSubmit() {
        this.$refs.artForm.validate(async (valid) => {
          if (valid) {
            await goodManage.addWork(this.workForm);
            if (this.$refs.workPage) await this.$refs.workPage.refresh();
            await this.closeWorkWind();
          }
        });
      },
      async submit() {
        this.$refs.workForm.validate(async (valid) => {
          if (valid) {
            if (this.updWorkId) {
              await goodManage.updWork(this.updWorkId, this.workForm);
            } else {
              const res = await goodManage.addWork(this.workForm);
              console.log(this.$refs.workPage);
            }
            if (this.$refs.workPage) await this.$refs.workPage.refresh();
            await this.closeWorkWind();
          }
        });
      },
      async dialogConfirm() {
        this.$refs.dataParams.validate(async (valid) => {
          if (valid) {
            let res = null;
            if (this.updId) {
              res = await goodManage.updStadiums(this.updId, {
                ...this.params,
              });
            } else {
              res = await goodManage.setStadiums({
                ...this.params,
              });
            }
            if (res) {
              this.isShowDialog = false;
              this.updId = '';
              this.refresh();
            }
          }
        });
      },
      onClose() {
        this.params = {
          name: '',
          introduction: '',
        };
        this.updId = '';
      },
    },
  };
</script>

<style lang="less" scoped>
  // .subTable {
  //   display: flex;
  //   justify-content: space-between;
  // }
  .add {
    border: 1px solid #dcdfe6;
    display: inline-block;
    line-height: 10px;
    border-radius: 5px;
    cursor: pointer;
    padding: 5px;
    &:hover {
      color: white;
      background-color: #409eff;
    }
  }
  .menu {
    position: absolute;
    top: 0;
    left: 0;
    background-color: white;
    border-radius: 10px;
    box-shadow: 2px 2px 10px rgba(0, 0, 0, 0.3);
    overflow: hidden;
    z-index: 999;
    & > div {
      padding: 10px 40px;
      border-bottom: 1px solid #eee;
      &:last-child {
        border-bottom: none;
      }
      &:hover {
        cursor: pointer;
        background-color: #409eff;
        color: white;
      }
    }
  }
  .good-container {
    height: 100%;
    .good-top {
      display: flex;
      align-items: center;
      justify-content: space-between;
      .good-search {
        display: flex;
      }
    }
  }
</style>
